package com.sc.admin.service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sc.admin.mapper.GoodsCatMapper;
import com.sc.admin.mapper.GoodsMapper;
import com.sc.admin.pojo.Goods;
import com.sc.admin.pojo.GoodsCat;
import com.sc.admin.pojo.SearchGoods;
import com.sc.admin.utils.IDUtils;

@Service
public class GoodsServiceImpl implements GoodsService {
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private GoodsCatMapper goodsCatMapper;
	@Autowired
	private JmsTemplate template;
	
	@Override
	public void add(Goods goods) {
		goods.setId(IDUtils.createGoodsId());
		goodsMapper.insertSelective(goods);
		
		GoodsCat goodsCat = goodsCatMapper.selectByPrimaryKey(goods.getCid());
		//添加商品索引服务（因为服务接口是http的协议，所以调用很方便）
		//具体我不演示了，这种方法也可以，不过会阻塞线程
		/*RestTemplate template = new RestTemplate();
		template.ex*/
		//我们可以用发送消息来做
		SearchGoods sg = SearchGoods.toSearchGoods(goods, goodsCat.getName());
		
		template.send(new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				Message message = session.createTextMessage(JSON.toJSONString(sg));
				return message;
			}
		});
	}

}
